package org.groupg.project.shell;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.apache.groovy.util.Arrays;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ComplexGroovyShellExample {
    public static void main(String[] args) {
        // 创建 GroovyShell 实例
        GroovyShell shell = new GroovyShell();

        String shellStr = """
                // complex_script.groovy
                
                class Employee {
                    String name
                    int age
                    String department
                    double salary
                
                    def getDetails() {
                        return "Name: ${name}, Age: ${age}, Department: ${department}, Salary: ${salary}"
                    }
                }
                
                def processEmployees(employees, bonusRate) {
                    def result = []
                    employees.each { emp ->
                        double bonus = emp.salary * bonusRate
                        result << "${emp.getDetails()}, Bonus: ${bonus}"
                    }
                    return result
                }
                """;

        // 创建 Binding 实例，并设置复杂变量
        Binding binding = new Binding();

        // 创建员工列表
        List<Map<String, Object>> employees = new ArrayList<>();
        Map<String, Object> emp1 = new HashMap<>();
        emp1.put("name", "Alice");
        emp1.put("age", 30);
        emp1.put("department", "Engineering");
        emp1.put("salary", 80000);

        Map<String, Object> emp2 = new HashMap<>();
        emp2.put("name", "Bob");
        emp2.put("age", 40);
        emp2.put("department", "Sales");
        emp2.put("salary", 70000);

        employees.add(emp1);
        employees.add(emp2);

        // 将员工列表和奖金率设置为 Binding 变量
        binding.setVariable("employees", employees);
        binding.setVariable("bonusRate", 0.10);

        try {
            // 解析 Groovy 脚本，同时传入 Binding
            Script script = shell.parse(shellStr, binding);

            // 调用 processEmployees 方法
            Object result = script.invokeMethod("processEmployees", new Object[]{employees,0.10});

            // 输出结果
            System.out.println("Processed Employees:");

            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}